package com.ce.pms;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.Random;

import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ce.pms.common.model.SysInfo;
import com.ce.pms.exception.BusinessException;
import com.ce.util.BlankUtil;
import com.ce.util.DateUtil;

/**
 *
 * 功能描述: DBUnitTool
 * <p>版权所有：中企动力
 * <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
 *
 * @author  胡煦
 * Created on：  2008-6-3
 * @author  付湘辉
 * update on：  2008-6-5
 * why: 重构，增加jdbc_url，jdbc_username，jdbc_password，jdbc_driver_class，init()
 */
public class DBUnitTool{

	protected JdbcDatabaseTester databaseTester;
	protected static ApplicationContext applicationContext =  new ClassPathXmlApplicationContext(getApplicationContextStr());
	protected String jdbc_url;
	protected String jdbc_username;
	protected String jdbc_password;
	protected String jdbc_driver_class;

	final private String configPath
	    = "src"+File.separator+"test"+File.separator+"resources"+File.separator+"config"+File.separator+"jdbcTest.properties";

	private static String[] getApplicationContextStr() {
		//return new String[] { "spring/*.xml","spring-conf/*.xml","struts-spring-conf/*.xml" };
		return new String[] {"modules/spring_test.xml","modules/**/spring-conf/*Context.xml","modules/**/struts-spring-conf/*.xml"};
	}

	public String getJdbc_driver_class() {
		return jdbc_driver_class;
	}

	public void setJdbc_driver_class(String jdbc_driver_class) {
		this.jdbc_driver_class = jdbc_driver_class;
	}

	public String getJdbc_password() {
		return jdbc_password;
	}

	public void setJdbc_password(String jdbc_password) {
		this.jdbc_password = jdbc_password;
	}

	public String getJdbc_url() {
		return jdbc_url;
	}

	public void setJdbc_url(String jdbc_url) {
		this.jdbc_url = jdbc_url;
	}

	public String getJdbc_username() {
		return jdbc_username;
	}

	public void setJdbc_username(String jdbc_username) {
		this.jdbc_username = jdbc_username;
	}

	public DBUnitTool() {

		// load DaoFactory
		// DaoFactory.buildDI();

		init();

	}

	/**
	 *
	 * 功能描述: 初始化
	 *
	 * @author 付湘辉
	 * Created on:2008-6-5
	 *
	 * 修改原因：
	 * @return void 返回结果
	 */
	public void init(){
		InputStream in = null;
		Properties p = null;
		try {
			in = new FileInputStream(this.configPath);

			p = new Properties();

			p.load(in);

			jdbc_url = p.getProperty("jdbc.url")+"&sessionVariables=FOREIGN_KEY_CHECKS=0";
			jdbc_driver_class = p.getProperty("jdbc.driverClassName");
			jdbc_username = p.getProperty("jdbc.username");
			jdbc_password = p.getProperty("jdbc.password");
			in.close();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (InvalidPropertiesFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		databaseTester = new JdbcDatabaseTester(jdbc_driver_class,
				jdbc_url, jdbc_username, jdbc_password);
	}

	@Before
	public void setUp() throws Exception {

		// initialize your dataset here

		//String[] classPath = new String[] {"resource/modules/spring.xml","resource/modules/**/spring-conf/*.xml","resource/modules/**/struts-spring-conf/*.xml"};

		String[] dataSetPaths = getDataSetFilePaths();

		IDataSet[] dataSet = new IDataSet[dataSetPaths.length];

		for (int i = 0; i < dataSetPaths.length; i++) {

			String path = dataSetPaths[i].startsWith("/") ? dataSetPaths[i]
					: "/" + dataSetPaths[i];
			dataSet[i] = new FlatXmlDataSet(DBUnitTool.class
					.getResourceAsStream(path));

		}

		CompositeDataSet compositeDateSet = new CompositeDataSet(
				(IDataSet[]) dataSet);

		databaseTester.setDataSet(compositeDateSet);
		// will call default setUpOperation
		databaseTester.setSetUpOperation(setUpOp());
		databaseTester.onSetup();
	}

	@After
	public void tearDown() throws Exception {
		databaseTester.setTearDownOperation(tearDownOp());
		databaseTester.onTearDown();
	}

	/**
	 *
	 * 功能描述: 获取xml数据集，建议子类覆盖此方法
	 *
	 * @author 付湘辉
	 * Created on:2008-6-5
	 *
	 * 修改原因：
	 * @return String[] 返回结果
	 */
	protected String[] getDataSetFilePaths() {
		return new String[] { "SEC_DICT.xml" };
	}

	/**
	 *
	 * 功能描述: 测试方法运行前数据操作，<b>DatabaseOperation.NONE<b>表示什么都不做<br>建议子类覆盖此方法
	 *
	 * @author 付湘辉
	 * Created on:2008-6-5
	 *
	 * 修改原因：
	 * @return DatabaseOperation 返回结果
	 */
	protected DatabaseOperation setUpOp() {
		return DatabaseOperation.NONE;
	}

	/**
	 *
	 * 功能描述: 测试方法运行后数据操作，<b>DatabaseOperation.NONE<b>表示什么都不做<br>，建议子类覆盖此方法
	 *
	 * @author 付湘辉
	 * Created on:2008-6-5
	 *
	 * 修改原因：
	 * @return DatabaseOperation 返回结果
	 */
	protected DatabaseOperation tearDownOp() {
		return DatabaseOperation.NONE;
	}

	/**
	 *
	 * 功能描述: 得到 jdbc 连接URL
	 *
	 * @author 付湘辉
	 * Created on:2008-6-5
	 *
	 * 修改原因：
	 * @return String
	 */
	@Deprecated
	private String databaseUrl() {
		return "jdbc:mysql://192.168.18.253:3306/pmsdev?useUnicode=true&characterEncoding=utf-8&noAccessToProcedureBodies=true";
	}

	/**
	 *
	 * 功能描述: 建立
	 *
	 * @author 付湘辉
	 * Created on:2008-7-2
	 *
	 * 修改原因：
	 * @param creator
	 * @return SysInfo 返回结果
	 */
	protected SysInfo createInfo(Long creator){
		SysInfo info = new SysInfo();
		info.setCreator(creator);
		info.setSysDate(DateUtil.getCurrentDate());

		return info;
	}

	/**
	 *
	 * 功能描述: 修改
	 *
	 * @author 付湘辉
	 * Created on:2008-7-2
	 *
	 * 修改原因：
	 * @param sysInfo
	 * @param modifier
	 * @return SysInfo 返回结果
	 */
	protected SysInfo modifyInfo(SysInfo sysInfo,Long modifier){
		sysInfo.setModifier(modifier);
		sysInfo.setModifyDate(DateUtil.getCurrentDate());
		return sysInfo;
	}

	/**
     * 功能描述:   <br>
     *
     * @param e
     *
     * Create author：付湘辉  <br>
     * Create on:2008-8-3  <br>
     * Edit author：  <br>
     * Edit on:    <br>
     * Why:     <br>
     */
	protected void dealBusinessException(BusinessException be,String ... strings) {
        be.printStackTrace();
        if (!BlankUtil.isBlank(strings)) {
            if (strings[0] != null) {
                if (!strings[0].equals(be.getMessage())) {
                    Assert.fail("预期异常消息KEY是： "+strings[0]+" 实际是： "+be.getMessage());
                }
            }
        }
    }

	/**
     *
     * 功能描述:   <br>
     *
     * @param e
     * @param info
     * @param eType
     *
     * Create author：付湘辉  <br>
     * Create on:2008-8-3  <br>
     * Edit author：  <br>
     * Edit on:    <br>
     * Why:     <br>
     */
	protected void dealException(Exception e,String ... strings){
        if (e instanceof BusinessException) {
            dealBusinessException((BusinessException)e,strings);
        } else {
        	e.printStackTrace();
            Assert.fail("测试未通过，异常信息--->"+e.getMessage());
        }
    }

	/**
	 * 功能描述: 生成一个随机字符串,长度不超过24个字符 <br>
	 * @return
	 *
	 * Create author:付湘辉 <br>
	 * Create on:2008-8-7  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	protected String generationRandomString() {
        Random rand=new Random(System.currentTimeMillis());
        SimpleDateFormat stringFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String date=stringFormat.format(new Date());
        int temp=rand.nextInt();
        temp = java.lang.Math.abs(temp);
        return date + temp;
    }

}
